package com.xs.project.service.impl;

import com.xs.project.cache.UserCacheMap;
import com.xs.project.common.Result;
import com.xs.project.email.MailServiceImpl;
import com.xs.project.mapper.LoginMapper;
import com.xs.project.pojo.vo.CourseReq;
import com.xs.project.pojo.vo.LoginReq;
import com.xs.project.pojo.vo.SubExamTitle;
import com.xs.project.pojo.vo.SubExamTitleReq;
import com.xs.project.pojo.vo.resp.*;
import com.xs.project.service.LoginService;
import com.xs.project.utils.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private LoginMapper loginMapper;

    @Resource
    private MailServiceImpl mailServiceImpl;
    @Override
    public Result<UserInfoResp> login(LoginReq req) {
        UserInfoResp userInfoResp = loginMapper.selectUser(req);
        if (userInfoResp == null){
            return Result.fail("用户名或密码错误");
        }
        return Result.success(userInfoResp);
    }

    @Override
    public Result<Boolean> register(LoginReq req) {
        loginMapper.insertUser(req);
        return Result.success(true);
    }

    @Override
    public Result<Boolean> resPassword(LoginReq req) {
        Object o = UserCacheMap.get(req.getEmailNum());
        if (o == null){
            return Result.fail("验证码失效");
        }
        UserCacheMap.remove(req.getEmailNum());
        loginMapper.updateUser(req);
        return Result.success(true);
    }

    @Override
    public Result<List<CourseVo>> getCourseList(CourseReq request) {
        buildParam(request);
        List<CourseVo> list = loginMapper.selectCourseList(request);
        long skipSize = (long) request.getPageSize() * (request.getPageNum() - 1); // 计算需要跳过的元素数量

        List<CourseVo> pageRes = list.stream()
                .skip(skipSize)
                .limit(request.getPageSize())
                .collect(Collectors.toList());
        for (CourseVo re : pageRes) {
            Integer count = loginMapper.selectStudentNum(re.getId());
            re.setSelectTotal(count == null ? 0 : count);
            re.setCourseTypeDesc("1".equals(re.getCourseType()) ? "文学" : "科技");
            re.setCourseTimeStr(DateUtil.getDateStr(re.getCourseTime()));
            String coursePoint = re.getCoursePoint();
            String courseTypeDesc = re.getCourseTypeDesc();
            List<String> tags = new ArrayList<>();
            tags.add(coursePoint+"学分");
            tags.add(courseTypeDesc);
            re.setTags(tags);
        }
        return Result.success(pageRes,list.size());
    }

    private void buildParam(CourseReq request) {
        String condition1 = request.getCondition1();
        if ("人文".equals(condition1)){
            request.setCourseType("1");
        }
        if ("科技".equals(condition1)){
            request.setCourseType("2");
        }
        String condition2 = request.getCondition2();
        if ("高难度".equals(condition2)){
            request.setCourseStar("5");
        }
        if ("中难度".equals(condition2)){
            request.setCourseStar("4");
        }
        String condition3 = request.getCondition3();
        if ("5分".equals(condition3)){
            request.setCoursePoint("5");
        }
        if ("3分".equals(condition3)){
            request.setCoursePoint("3");
        }
        if ("2分".equals(condition3)){
            request.setCoursePoint("2");
        }
    }

    @Override
    public Result<List<CourseVo>> getHotCourseList(CourseReq request) {
        List<CourseVo> list = loginMapper.selectCourseList(request);
        for (CourseVo re : list) {
            Integer count = loginMapper.selectStudentNum(re.getId());
            re.setSelectTotal(count == null ? 0 : count);
            re.setCourseTypeDesc("1".equals(re.getCourseType()) ? "文学" : "科技");
            re.setCourseTimeStr(DateUtil.getDateStr(re.getCourseTime()));
        }
        list.sort(Comparator.comparingInt(CourseVo::getSelectTotal));
        long skipSize = (long) request.getPageSize() * (request.getPageNum() - 1); // 计算需要跳过的元素数量
        List<CourseVo> pageRes = list.stream()
                .skip(skipSize)
                .limit(request.getPageSize())
                .collect(Collectors.toList());

        return Result.success(pageRes,list.size());
    }

    @Override
    public Result<CourseDetailVo> getCourseDetail(String courseId,String userId) {
        CourseDetailVo res = new CourseDetailVo();
        CourseVo vo = loginMapper.selectCourseByid(courseId);
        vo.setCourseTimeStr(DateUtil.getDateStr(vo.getCourseTime()));
        vo.setCourseTypeDesc("1".equals(vo.getCourseType()) ? "文学" : "科技");
        List<CourseSubVo> list = loginMapper.selectCourseSubList(courseId,userId);
        if (!CollectionUtils.isEmpty(list)){
            for (CourseSubVo courseSubVo : list) {
                if (courseSubVo.getCourseSubTime() == null){
                    continue;
                }
                if (!StringUtils.isEmpty(courseSubVo.getPoint())){
                    courseSubVo.setPoint(courseSubVo.getPoint()+"分");
                }
                courseSubVo.setCourseSubTimeStr(DateUtil.getDateStr(courseSubVo.getCourseSubTime()));
            }
            res.setSubVoList(list);
        }
        res.setCourseVo(vo);

        return Result.success(res);
    }

    @Override
    public Result<ExamVo> getExamDetail(String examId) {
        ExamVo vo = loginMapper.getExamDetail(examId);
        if (vo == null){
            return Result.success(null);
        }
        vo.setExamTimeStr(DateUtil.getDateStr(vo.getExamTime()));
        List<ExamTitleVo> titleVoList = loginMapper.getExamTitle(examId);
        if (CollectionUtils.isEmpty(titleVoList)){
            return Result.success(vo);
        }
        buildTitleVo(titleVoList,vo);
        return Result.success(vo);
    }

    @Override
    public Result<Boolean> subExamDetail(SubExamTitleReq req) {
        SubExamTitle subExamTitle = req.getList().get(0);
        if (checkHasSub(subExamTitle)){
            return Result.fail("试卷已经提交过了");
        }
        List<SubExamTitle> list = req.getList();
        for (SubExamTitle examTitle : list) {
            ExamTitleEnt vo = loginMapper.getCorrectAnswer(examTitle);
            if ("2".equals(vo.getExamType())){
                examTitle.setExamTitlePoint("0");
                examTitle.setHandleStatus("0");
                loginMapper.insertExamTitle(examTitle);
                continue;
            }
            examTitle.setHandleStatus("1");
            if (vo.getExamOptionCorrect().equals(examTitle.getExamTitleValue())){
                examTitle.setExamTitlePoint(vo.getExamPoint());
            }else {
                examTitle.setExamTitlePoint("0");
            }
            loginMapper.insertExamTitle(examTitle);
        }
        return Result.success(true);
    }

    @Override
    public Result<String> emailCode(String emailNum) {
        String code = UUID.randomUUID().toString().replace("-", "").substring(0,6);
        mailServiceImpl.sendSimpleText(emailNum,"密码重置邮件", "您的验证码："+code+",注册后失效");
        UserCacheMap.put(emailNum,code);
        return Result.success("验证码已发送至您的邮箱");
    }

    @Override
    public Result<Integer> getExamIdByUserId(String userId) {
        Integer examId = loginMapper.getExamIdByUserId(userId);
        return Result.success(examId);
    }

    @Override
    public Result<Boolean> saveHomeWork(HomeWorkVo courseResourceVo) {
        loginMapper.saveHomeWork(courseResourceVo);
        return Result.success(true);
    }

    @Override
    public Result<String> getExamRes(String userId) {
        ExamResVo vo = loginMapper.selectCourseByUserId(userId);
        if (vo == null || vo.getUserPoint() == null){
            return Result.success("");
        }
        String res = "您在" + vo.getCourseName() + vo.getExamName() + "的考试得分为：" + vo.getUserPoint() + "分";
        return Result.success(res);
    }

    private boolean checkHasSub(SubExamTitle subExamTitle) {
        Integer size = loginMapper.selectExamTitle(subExamTitle);
        return size > 0;
    }

    private void buildTitleVo(List<ExamTitleVo> titleVoList,ExamVo vo) {
        int i = 1;
        for (ExamTitleVo titleVo : titleVoList) {
            String examType = titleVo.getExamType();
            if ("1".equals(examType)){
                titleVo.setExamTypeStr("选择题");
                String[] split = titleVo.getExamOption().split(",");
                titleVo.setOptions(Arrays.asList(split));
            }else{
                titleVo.setExamTypeStr("问答题");
            }
            titleVo.setExamTitle(i+"."+titleVo.getExamTitle() + "("+titleVo.getExamPoint()+"分)");
            i++;
        }
        vo.setExamTitleVo(titleVoList);
    }
}
